<?php
class M_qin_subscribes extends Cemvc_Db_MysqlDb{
  public $PrimaryKey='id';
  /*CEPHP会在要需要时查询主键，但主动设置主键可以使程序执行更快*/

  public function __construct()
  {
    parent::__construct();
    
  }

  /* 
   * */
  public function getWithEmail($email)
  {
    return $this->where(array("email = '$email'"))->fetchOne();
  }
  public function get($id)
  {
    return $this->where(array("id = '$id'"))->fetchOne();
  }
  /**  
   * description: insert an email and set validate state to 'init'
   * @params $email which you want to subscribe
   * @return $subscribe array
   * */
  public function add($email)
  {
    $param = array();
    $param["email"] = addslashes($email);
    $param['validate'] = SUBSCRIBE_STATE_INIT;
    $param['pass'] = substr(md5(rand(0, 100).date('gis')), 0, 7);

    $res = $this->insert($param);
    return $this->get($res["last_insert_id()"]);
  }

  /** 
   * description: if $email and $pass matched, set the validate to 'validate'
   * @params $email
   * @params $pass
   * @return 0 for success, otherwise failed
   * */
  public function validate($email, $pass)
  {
    $subscribe = $this->getWithEmail($email);
    M_Tools::del_cache($this->LastQueryString);
    $intval = time() - strtotime($subscribe['date']);

    include_once WEB_ROOT."/Public/Set/Email.php";
    if (!$subscribe || !$subscribe['id'])
      return SUBSCRIBE_EMAIL_NOT_FOUND;
    else if ($subscribe['pass'] != $pass)
      return SUBSCRIBE_PASS_NOT_MATCH;
    else if ($subscribe['validate'] == SUBSCRIBE_STATE_VALIDATE)
      return SUBSCRIBE_VALIDATE_OK;
    else if ($intval > SUBSCRIBE_VALIDATE_EXPIRED)
      return SUBSCRIBE_EXPIRED;
    else
      {
	$this->where(array("id = '".$subscribe['id']."'"))->update(array("validate"=>SUBSCRIBE_STATE_VALIDATE));
	$subscribe = $this->getWithEmail($email);
	if ($subscribe["validate"] == SUBSCRIBE_STATE_VALIDATE)
	  return SUBSCRIBE_VALIDATE_OK;
	else
	  return SUBSCRIBE_VALIDATE_FAILED;
      } 
  }

  /** 
   * description: for people who subscribe before, but expired (not validate in 24 hours)
   *  only update the 'date' field with $email
   * */
  public function resubscribe($email)
  {
    $this->where("email = '$email'")->update("date = '".date('Y-m-d G:i:s')."'");
  }
}